package main

import (
	"fmt"
	"github.com/hashicorp/consul/api"
)

// 注册服务
func CousulRegister(address, name string, port int, tags []string, id string) error {
	cfg := api.DefaultConfig()
	cfg.Address = "127.0.0.1:8500"
	client, err := api.NewClient(cfg)
	if err != nil {
		panic(err)
	}
	check := &api.AgentServiceCheck{
		HTTP:                           "http://127.0.0.1:8021/health",
		Timeout:                        "5s",
		Interval:                       "5s",
		DeregisterCriticalServiceAfter: "10s",
	}
	registration := new(api.AgentServiceRegistration)
	registration.Name = name
	registration.Address = address
	registration.Tags = tags
	registration.Port = port
	registration.ID = id
	registration.Check = check

	err = client.Agent().ServiceRegister(registration)
	if err != nil {
		panic(err)
	}
	return nil
}

// 获取服务
func AllServices() {
	cfg := api.DefaultConfig()
	cfg.Address = "127.0.0.1:8500"
	client, err := api.NewClient(cfg)
	if err != nil {
		panic(err)
	}
	services, err := client.Agent().Services()
	if err != nil {
		panic(err)
	}
	for key, _ := range services {
		fmt.Println(key)
	}

}

func FilterService() {
	cfg := api.DefaultConfig()
	cfg.Address = "192.168.22.146:8500"
	client, err := api.NewClient(cfg)
	if err != nil {
		panic(err)
	}
	services, _ := client.Agent().ServicesWithFilter(`Service=="go-shop"`)
	if err != nil {
		return
	}
	fmt.Println(services)
	for key, val := range services {
		fmt.Println(key, val)
	}
}

func main() {
	_ = CousulRegister("127.0.0.1", "go-shoptest", 8021, []string{"xxx"}, "go-shoptest")
	//fmt.Println()
	//AllServices()
	//FilterService()
}
